package com.goldze.mvvmhabit.ui.network;

import android.content.Context;

import com.goldze.mvvmhabit.data.DemoRepository;
import com.goldze.mvvmhabit.data.source.HttpDataSource;
import com.goldze.mvvmhabit.data.source.LocalDataSource;
import com.goldze.mvvmhabit.entity.DemoEntity;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * @author: bruce
 * @project: MVVMHabit-master
 * @package: com.goldze.mvvmhabit.ui.network
 * @description:
 * @date: 2020/4/25
 * @time: 11:28
 */
public class NetWorkManager {

    public static void requestNetData(final Observable observable, BaseViewModel model, final netHttpCallBack callBack){
//        DemoRepository.getInstance(httpDataSource,mLocalDataSource).demoGet()

        //可以调用addSubscribe()添加Disposable，请求与View周期同步
        observable.compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(model)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
                    }
                })
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse response) throws Exception {
                        callBack.success(response);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        callBack.fail(throwable);
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
//                        callBack.fail();
                    }
                });
    }


    public interface netHttpCallBack{
        void success(BaseResponse response);
        void fail(Throwable throwable);
    }
}
